from distutils.command.config import config
from http.client import responses
import requests
from requests import session
from api.longin import LoginAPI
import random
import hashlib
import config
from lib.log import Log


class MBlogin():
    # 账号密码加密
    @classmethod
    def bParams(cls, mobileNo):
        mobileNo = str(mobileNo)  # 将手机号转换为字符串
        pwd = mobileNo[-6:]  # 取手机号的最后六位数字作为密码
        # 生成三位随机数
        rand = str(random.randint(100, 999))
        # 第一次 MD5 加密
        md5_1 = hashlib.md5()
        md5_1.update(pwd.encode("utf-8"))
        md5_pwd1 = md5_1.hexdigest()
        # 拼接一个固定字符串进行二次加密
        pwd2 = pwd + "2a01QvZ617m9"
        md5_2 = hashlib.md5()  # 创建新的 MD5 对象
        md5_2.update(pwd2.encode("utf-8"))
        md5_pwd2 = md5_2.hexdigest()
        # 拼接所有加密结果与随机数
        md5_pwd = md5_pwd1 + rand + md5_pwd2
        # 输出最终的加密结果
        print(md5_pwd)

        login_params = {
            "desc": "登录成功",
            "param": {
                "loginInfo": {
                    "password": md5_pwd,
                    "mobileNo": mobileNo,
                    "deviceId": "D414C492-80A2-4615-A640-B1E180036031",
                    "clientType": "ios",
                    "userAgent": "KKLOnLine/5.28.0 (iPhone; iOS 13.6; Scale/3.00; appVersion 5.28.0; XHX)",
                    "loginIp": "172.17.2.49"
                }
            },
            "testexpect": "操作成功"
        }
        return login_params
    # 登录
    def mbLogin(self, mobileno):
        self.session = requests.session()
        self.params = self.bParams(mobileno)["param"]  # 调用函数
        responses = LoginAPI().kklLogin(self.session, self.params)
        response = responses.json()

        if responses.status_code != 200:
            raise Exception(f"Login failed with status: {responses.status_code}, Response: {response}")

        try:
            token = response['data']['resultObject']['token']
            config.prints(responses)
            print(f'{mobileno}:token = {token}')
            Log(f'{mobileno}:token = {token}')

        except KeyError as e:
            Log(f"Key error: {str(e)}. Response data: {response}")
            raise KeyError(f"Key error: {str(e)}. Response data: {response}")

        finally:
            self.session.close()

        return token


if __name__ == "__main__":
    login = MBlogin().mbLogin(13221080002)